<?php
declare (strict_types=1);

namespace app\api\controller\chat;

use app\common\model\ai\AiClubUser;
use app\common\model\ai\AiUserChat;
use app\common\model\ai\AiUserClubChat;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\worker\Server;
use Workerman\Lib\Timer;

// define('HEARTBEAT_TIME', 30);// 心跳间隔
class ChatController extends Server
{
    protected        $socket         = 'websocket://0.0.0.0:2345';
    protected        $redis;
    protected static $heartbeat_time = 50;
    // 声明属性 uidConnections
    protected array $uidConnections = [];

    public function onConnect($connection)
    {
        $this->redis = Cache::store('redis')->handler();
    }

    public function onWorkerStart($worker)
    {
        Timer::add(10, function () use ($worker) {
            $time_now = time();
            #这里统计下线人员的id
            $offline_user = [];

            foreach ($worker->connections as $connection) {
                // 有可能该connection还没收到过消息，则lastMessageTime设置为当前时间
                if (empty($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                    continue;
                }
                // 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
                // if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) {
                if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) {
                    #这里统计下线人员的id
                    $offline_user[] = $connection->uid;
                    #关闭连接
                    $connection->close();
                }

                #这里是一个用户下线后通知其他用户
                if (count($offline_user) > 0) {
                    $msg = ['type' => 'message', 'uid' => $connection->uid, "message" => "用户【" . implode(',', $offline_user) . "】下线了"];
                    $connection->send(json_encode($msg));
                }
            }
        });
    }

    public function onMessage($connection, $data)
    {
        #最后接收消息时间
        $connection->lastMessageTime = time();
        $msg_data                    = json_decode($data, true);
        if (!$msg_data) {
            return;
        }

        Log::error($data);

        #这里统计上线人员的id
        $online_user = [];

        $issee = 0;
        if ($msg_data['type'] == 'bind') {
            $from_id = $msg_data['uid'];
            $to_id   = $msg_data['to_uid'];
        } else {
            $from_id = $msg_data['from_id'];
            $to_id   = $msg_data['to_id'];
        }

        Log::error($this->redis->get('uid_' . $from_id));

        if (!$this->redis->get('uid_' . $from_id)) {
            $this->redis->set('uid_' . $from_id, $to_id);
            if ($this->redis->get('uid_' . $to_id) == $from_id) {
                $issee = 1;
            }
        } else {
            if ($this->redis->get('uid_' . $from_id) == $to_id && $this->redis->get('uid_' . $to_id) == $from_id) {
                $issee = 1;
            }
        }

        #绑定用户ID
        if ($msg_data['type'] == 'bind' && isset($msg_data['to_uid']) && !isset($connection->uid)) {
            $connection->uid                        = $msg_data['uid'];
            $online_user[]                          = $connection->uid;
            $this->uidConnections[$connection->uid] = $connection;
        } else if ($msg_data['type'] == 'text' && $msg_data['mode'] == 'single') {
            #单人发消息
            if ($this->redis->get('uid_' . $to_id) == $from_id) {
                if (isset($this->uidConnections[$msg_data['to_id']])) {
                    $conn = $this->uidConnections[$msg_data['to_id']];
                    $conn->send($data);
                }
            }
        }

        if ($msg_data['type'] == 'text' && $msg_data['mode'] == 'single') {
            if ($msg_data['content'] != '' && $msg_data['content'] != null) {
                $second = 0;
                if ($msg_data['is_audio'] ?? '' == true) {
                    //证明是音频
                    $second = $this->getAudioSeond($msg_data['content']);
                }
                //将发来的信息保存到数据库
                $info = [
                    'user_id'    => $msg_data['from_id'],
                    'be_user_id' => $msg_data['to_id'],
                    'content'    => $msg_data['content'],
                    'is_type'    => $msg_data['is_type'],
                    'second'     => $second,
                    'is_see'     => $issee,
                ];
                AiUserChat::create($info);
            }
        }

        //俱乐部
        if ($msg_data['type'] == 'bind' && isset($msg_data['club_id']) && !isset($connection->uid)) {
            $connection->uid                        = $msg_data['uid'];
            $online_user[]                          = $connection->uid;
            $this->uidConnections[$connection->uid] = $connection;
        }

        #群聊
        if ($msg_data['type'] == 'text' && $msg_data['mode'] == 'group') {
            #实际项目通过群号查询群里有哪些用户
            //俱乐部成员
            $club_user = AiClubUser::where(['club_id' => $msg_data['club_id'], 'to_examine' => 1, 'status' => 0, 'delete_time' => 0])->column('user_id');
            foreach ($club_user as $key => $val) {
                if ($val != $msg_data['from_id']) {
                    if (isset($this->uidConnections[$val])) {
                        $conn = $this->uidConnections[$val];
                        $conn->send($data);
                    }
                }

            }
            if ($msg_data['content'] != '' && $msg_data['content'] != null) {
                $second = 0;
                if ($msg_data['is_audio'] == true) {
                    //证明是音频
                    $second = $this->getAudioSeond($msg_data['content']);
                }
                //将发来的信息保存到数据库 俱乐部
                $info = [
                    'user_id' => $msg_data['from_id'],
                    'club_id' => $msg_data['club_id'],
                    'content' => $msg_data['content'],
                    'is_type' => $msg_data['is_type'],
                    'second'  => $second,
                    'is_see'  => 0,
                ];
                AiUserClubChat::create($info);
            }

        }
    }

    //获取音频时常
    public function getAudioSeond($path)
    {
        include_once app()->getRootPath() . 'vendor/getID3-master/getid3/getid3.php';
        $getID3       = new \getID3();//实例化类
        $path         = app()->getRootPath() . 'public' . $path;
        $ThisFileInfo = $getID3->analyze($path);//分析文件，$path为音频文件的地址
        $fileduration = $ThisFileInfo['playtime_seconds'];//这个获得的便是音频文件的时长
        $time         = (int)ceil($fileduration);
        return $time;
    }

    /**
     * 当连接断开时触发的回调函数
     */
    public function onClose($connection)
    {
        $this->redis->del('uid_' . $connection->uid);
    }

}

